package com.ljh.mall.ware.service.impl;

import com.ljh.common.constant.WareConstant;
import com.ljh.mall.ware.entity.PurchaseDetailEntity;
import com.ljh.mall.ware.service.PurchaseDetailService;
import com.ljh.mall.ware.service.WareSkuService;
import com.ljh.mall.ware.vo.MergeVO;
import com.ljh.mall.ware.vo.PurchaseDoneVO;
import com.ljh.mall.ware.vo.PurchaseItemDoneVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljh.common.utils.PageUtils;
import com.ljh.common.utils.Query;

import com.ljh.mall.ware.dao.PurchaseDao;
import com.ljh.mall.ware.entity.PurchaseEntity;
import com.ljh.mall.ware.service.PurchaseService;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService detailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询采购单的状态为 新建 或者 已分配 的采购单信息
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> queryWrapper = new QueryWrapper<>();
        // 添加查询的条件
        queryWrapper.eq("status",0).or().eq("status",1);
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    @Override
    public Integer merge(MergeVO mergeVO) {
        Long purchaseId = mergeVO.getPurchaseId();
        if (purchaseId == null){
            // 新建采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        // 只有新建 或者 分配 才能 合单
        PurchaseEntity purchaseEntity = this.getById(purchaseId);
        if(purchaseEntity.getStatus() > WareConstant.PurchaseStatusEnum.RECEIVE.getCode()){
            // 该菜单不能合单
            return -1;
        }
        // 整合菜单需求单
        List<Long> items = mergeVO.getItems();
        final long finalPurchaseId = purchaseId;
        // 将所有的 采购需求 合并。统一采购单
        List<PurchaseDetailEntity> list = items.stream().map(i ->{
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            // 更新每一条 需求单的 采购单编号
            detailEntity.setId(i);
            detailEntity.setPurchaseId(finalPurchaseId);
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGED.getCode());
            return detailEntity;
        }).filter(id ->{
            // 过滤掉 只剩新建 和已分配
            PurchaseDetailEntity item = detailService.getById(id);
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.CREATED.getCode() ||
                    item.getStatus() == WareConstant.PurchaseDetailStatusEnum.ASSIGED.getCode()) {
                return true;
            }
            return false;
        }).collect(Collectors.toList());
        if (list != null && list.size() > 0){
            detailService.updateBatchById(list);
        }
        // 新对应的采购单
        PurchaseEntity entity = new PurchaseEntity();
        entity.setId(purchaseId);
        this.updateById(entity);
        return 1;
    }

    /**
     * 领取采购单
     * @param ids 采购单id
     */
    @Override
    public void received(List<Long> ids) {
        // 领取采购单的状态  只能是 新建 或者  已分配
        List<PurchaseEntity> list = ids.stream().map(id -> {
            return this.getById(id);
        }).filter(item -> {
            if (item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
            item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGED.getCode()) {
                return true;
            }
            return false;
        }).map(item -> {
            // 更新采购单的状态为 已领取
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            return item;
        }).collect(Collectors.toList());

        this.updateBatchById(list);
          for (Long id: ids) {
              // 根据采购单id 找到对应的采购项对象
              List<PurchaseDetailEntity> detailEntities = detailService.listDetailByPurchaseId(id);
              List<PurchaseDetailEntity> collect = detailEntities.stream().map(item -> {
                PurchaseDetailEntity entity = new PurchaseDetailEntity();
                entity.setId(item.getId());
                // 正在采购
                entity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return entity;
              }).collect(Collectors.toList());
              detailService.updateBatchById(collect);
          }

    }

    @Override
    public void done(PurchaseDoneVO vo) {
        // 获取采购单编号
        Long id = vo.getId();

        // 2.改变采购项的状态
        Boolean flag = true;
        List<PurchaseItemDoneVO> items = vo.getItems();
        List<PurchaseDetailEntity> list = new ArrayList<>();
        for (PurchaseItemDoneVO item:items){
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            // 获取采购需求的状态
            if(item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                // 该采购项采购出现了问题
                flag = false;
                detailEntity.setStatus(item.getStatus());
            } else {
                // 采购项采购成功
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                // 3.将  采购成功的采购需求  进入库操作
                // 入库需要什么 ？ 仓库！ 入谁？ 入多少？
                PurchaseDetailEntity entity = detailService.getById(item.getItemId());
                wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());

            }
            detailEntity.setId(item.getItemId());
            //将所有的采购需求 进行统一修改
            list.add(detailEntity);
        }
        // 将入库的 采购需求 的状态修改为已完成
        detailService.updateBatchById(list);

        // 1.改变采购单的状态
        //  如果入库成功
        // 如果采购需求异常
        PurchaseEntity purchaseEntity = new PurchaseEntity();

        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode()
                : WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());

        this.updateById(purchaseEntity);
    }

}